package com.daxin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.daxin.mapper.TransferMapper;
import com.daxin.mapper.WalletMapper;
import com.daxin.pojo.Transfer;
import com.daxin.pojo.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("transferService")
public class TransferServiceImpl implements TransferService{
    @Autowired
    private TransferMapper transferMapper;

    @Autowired
    private WalletMapper walletMapper;

    @Override
    @Transactional
    public void doTransfer(Transfer transfer) {
        transfer.setObb(UUID.randomUUID().toString().replace("-", "").substring(0,19));
        transferMapper.insert(transfer);

        String fromId = transfer.getFromId();
        String toId = transfer.getToId();
        Integer money = transfer.getMoney();

        UpdateWrapper<Wallet> updateWrapper1 = new UpdateWrapper();
        updateWrapper1.eq("dx_id", fromId);
        QueryWrapper queryWrapper1 = new QueryWrapper<>().eq("dx_id", fromId);
        Wallet walletForm = walletMapper.selectOne(queryWrapper1);
        walletForm.setMoney((walletForm.getMoney()-money));
        walletMapper.update(walletForm, updateWrapper1);

        UpdateWrapper<Wallet> updateWrapper2 = new UpdateWrapper();
        updateWrapper2.eq("dx_id", toId);
        QueryWrapper queryWrapper2 = new QueryWrapper<>().eq("dx_id", toId);
        Wallet walletTo = walletMapper.selectOne(queryWrapper2);
        walletTo.setMoney((walletTo.getMoney()+money));
        walletMapper.update(walletTo, updateWrapper2);

    }

    @Override
    public List<Transfer> findLast30DaysIn(String dxId) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -30);
        Date previousDate = now.getTime();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.gt("time", previousDate);
        queryWrapper.orderByAsc("time");
        queryWrapper.eq("to_id", dxId);
        List<Transfer> transferList = transferMapper.selectList(queryWrapper);
        return transferList;
    }


    public List<Transfer> findLast30DaysOut(String dxId) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -30);
        Date previousDate = now.getTime();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.gt("time", previousDate);
        queryWrapper.orderByAsc("time");
        queryWrapper.eq("from_id", dxId);
        List<Transfer> transferList = transferMapper.selectList(queryWrapper);
        return transferList;
    }


}
